import math

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from app01.sers import *


class ClassView(APIView):
    def post(self, request):
        ser = ClassSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功'})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'status': ser.errors})

    def get(self, request):
        class_num = int(request.GET.get('num', 1))
        class_size = 1
        queryset = Class.objects.all()[(class_num - 1) * class_size:class_num * class_size]
        count = Class.objects.count()
        size = math.ceil(count / class_size)
        ser = ClassSer(queryset, many=True)
        resp = {'data': ser.data, 'class_list': [x for x in range(1, size + 1)]}
        return Response(resp)


class ShowClassView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        queryset=Class.objects.filter(id=id)
        ser=ClassSer(queryset,many=True)
        return Response(ser.data)
